package com.cssy.xxkj.logic.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.byd.acegiext.domain.User;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.contants.BillTypeConstant;
import com.cssy.xxkj.logic.dao.LogicProductionPlanDAO;
import com.cssy.xxkj.logic.dao.LogicProductionPlanItemDAO;
import com.cssy.xxkj.logic.dao.LogicSalesDAO;
import com.cssy.xxkj.logic.entity.LogicProductionDispatchDO;
import com.cssy.xxkj.logic.entity.LogicProductionPlanDO;
import com.cssy.xxkj.logic.entity.LogicProductionPlanItemDO;
import com.cssy.xxkj.logic.entity.LogicSalesDO;
import com.cssy.xxkj.logic.service.ILogicProductionPlanService;
import com.cssy.yd.logic.util.MathUtil;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.DateUtils;
import com.plat.util.GlobalResLoader;
import com.plat.util.IDCodeTypeUtil;
import com.plat.util.SessionUtil;
import com.yuendong.sy.po.code.SyCode;
import com.yuendong.sy.service.code.impl.SyCodeService;
/**
 * 生产计划业务方法
 * @modify hf 
 *
 */
@Service("logicProductionPlanService")
public class LogicProductionPlanServiceImpl implements ILogicProductionPlanService {
	private static final Logger logger = Logger.getLogger(LogicProductionPlanServiceImpl.class);
	@Resource(name = "logicProductionPlanDAO")
	private LogicProductionPlanDAO logicProductionPlanDAO;
	
	@Resource(name = "logicSalesDAO")
	private LogicSalesDAO logicSalesDAO;
	
	@Resource(name = "logicProductionPlanItemDAO")
	private LogicProductionPlanItemDAO  logicProductionPlanItemDAO;
	
	@Resource(name = "syCodeService")
	private SyCodeService syCodeService;
	
	@Override
	public SearchResult findListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs=new SearchResult(scs);
		List<LogicProductionPlanDO>  list=logicProductionPlanDAO.find(scs);
		rs.setRecordCount(logicProductionPlanDAO.count(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer delete(String id, User user) throws SyBaseException {
		logicProductionPlanDAO.deleteLogicProductionPlanDOByPrimaryKey(id);
		return null;
	}

	@Override
	public Integer update(LogicProductionPlanDO t, User user) throws SyBaseException {
		t.setBizModifyName(user.getName());
		t.setBizModifyDate(new Date());
		t.setBizVersionMark(t.getBizVersion());
		t.setBizVersion(t.getBizVersion()+1);
		return logicProductionPlanDAO.updateLogicProductionPlanDO(t);
	}

	@Override
	public LogicProductionPlanDO save(LogicProductionPlanDO sodo, User user) throws SyBaseException {
		sodo.setBizCreatorName(user.getName());
		sodo.setBizCreatorDate(new Date());
		sodo.setBizVersion(1);
		logicProductionPlanDAO.insertLogicProductionPlanDO(sodo);
		return sodo;
	}

	@Override
	public LogicProductionPlanDO findListById(String id) throws SyBaseException {
		return logicProductionPlanDAO.findLogicProductionPlanDOByPrimaryKey(id);
	}

	

	@Override
	public Integer deleteBizRemoved(String id) throws SyBaseException {
		return logicProductionPlanDAO.deleteBizRemoved(id);
	}

	@Override
	public List<LogicProductionPlanItemDO> findPlanItemList(String id) throws SyBaseException {
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty(null);
		if(scs.getOrderBy()==null){
			scs.setOrderBy("(zd043Order+0)");
		}
		scs.addCondition("zd001ProPlanId", id, SearchCondition.OP_EQUAL);
		List<LogicProductionPlanItemDO>  list=logicProductionPlanItemDAO.find(scs);
		return list;
	}
	
	@Override
	public List<LogicProductionPlanItemDO> findItemListByExample(SearchConditions scs)throws SyBaseException{
		List<LogicProductionPlanItemDO> list=logicProductionPlanItemDAO.find(scs);
		return list;
	}

	@Override
	public void planSave(HttpServletRequest request, LogicProductionPlanDO curAP)
			throws SyBaseException {
		try {
			String itemdata = request.getParameter("itemdata");//物品数据
			String paramflag =request.getParameter("paramflag");
			curAP.setZd008Billstatus(paramflag);//单据状态
			List<LogicProductionPlanItemDO> Itemlist = JSONArray.parseArray(itemdata,LogicProductionPlanItemDO.class);
			User user = SessionUtil.getUser(request);
			//日期转换处理
			String zd005OrderDate = request.getParameter("zd005OrderDate");//订单日期
			if(StringUtils.isNotBlank(zd005OrderDate)){
				curAP.setZd005OrderDate(DateUtils.stringToDate(zd005OrderDate));
			}
			String zd006DeliveryDate = request.getParameter("zd006DeliveryDate");//交货日期
			if(StringUtils.isNotBlank(zd006DeliveryDate)){
				curAP.setZd006DeliveryDate(DateUtils.stringToDate(zd006DeliveryDate));
			}
			if (StringUtils.isBlank(curAP.getId())) {
					String id = IDCodeTypeUtil.getId();
					curAP.setId(id);
					curAP.setZd012WareStatus(0l);
					curAP.setZd013WhGetStatus(0l);
					curAP.setZd001FormCode(syCodeService.getCode(BillTypeConstant.PROPLAN,BillTypeConstant.PROPLAN,SyCode.DATE_YYMM,5));
					this.save(curAP,user);
					for (LogicProductionPlanItemDO ItemDO : Itemlist) {
						ItemDO.setZd001ProPlanId(id);
						ItemDO.setId(IDCodeTypeUtil.getId());
						logicProductionPlanItemDAO.insertLogicProductionPlanItemDO(ItemDO);
					}
					logger.info("新增生产计划单成功");
			} else {
					int rs=this.update(curAP, user);
					if(0==rs){
						throw new SyBaseException("您操作的单据数据发生了改变!请您重新打开编辑！");
					}
					if(Itemlist!=null&&!Itemlist.isEmpty()&&Itemlist.size()>0){
						logicProductionPlanItemDAO.deletePlanId(curAP.getId());
						List<LogicProductionPlanItemDO> list = findByIdItem(curAP,true);
						for(int i=0;i<Itemlist.size();i++){
							if(this.validateSubmit(list, Itemlist.get(i))){
								throw new SyBaseException("订单物料”"+Itemlist.get(i).getZd008MaterialsName()+"“下单总数量大于订单数量，不合法！");
							}
							Itemlist.get(i).setZd001ProPlanId(curAP.getId());
							Itemlist.get(i).setId(IDCodeTypeUtil.getId());
							logicProductionPlanItemDAO.insertLogicProductionPlanItemDO(Itemlist.get(i));
						}
					}
			}
			if(curAP.getZd008Billstatus().equals(BillStatusUtil.PROPLAN_BILL_STATUS_TWO)){
				LogicSalesDO sales = new LogicSalesDO();
				sales.setZd001FormCode(curAP.getZd002OriCode());
				List<LogicSalesDO> saleslist=logicSalesDAO.findListByExample(sales);
				if(saleslist!=null&&!saleslist.isEmpty()&&saleslist.size()>0){
					saleslist.get(0).setZd024Billstatus(BillStatusUtil.SES_STATUS_SEVEN);
					saleslist.get(0).setBizVersionMark(saleslist.get(0).getBizVersion());
					saleslist.get(0).setBizVersion(saleslist.get(0).getBizVersion()+1);
					int r=logicSalesDAO.updateLogicSalesDO(saleslist.get(0));
					if(r==0){
						throw new SyBaseException("您操作的原始单据数据发生了改变!请您重新打开编辑！");
					}
					logger.info("更新销售订单状态成功");
				}
			}
			logger.info("修改生产计划单成功");
		}catch(Exception e){
			e.printStackTrace();
			logger.error("操作生产计划单失败！");
			throw new SyBaseException(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
	}

	@Override
	public List<LogicSalesDO> findPiCode(String code) throws SyBaseException {
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty("removed");
		if(!StringUtils.isBlank(code)){
			scs.addCondition("zd002PiCode", code, SearchCondition.OP_EQUAL);
		}
		scs.addCondition("zd024Billstatus", "3", SearchCondition.OP_EQUAL);
		List<LogicSalesDO>  list=logicSalesDAO.find(scs);
		return list;
	}
	
	/**
	 * 验证退料数量是否合法
	 * @param list
	 * @param ItemDO
	 * @return
	 */
	private boolean validateSubmit(List<LogicProductionPlanItemDO> list,LogicProductionPlanItemDO ItemDO){
		BigDecimal bg = ItemDO.getZd013Quantity();
		if(list!=null&&!list.isEmpty()&&list.size()>0){
			for(int i=0;i<list.size();i++){
				if(ItemDO.getZd007MaterialsCode().equals(list.get(i).getZd007MaterialsCode())){
					bg=MathUtil.mathUtil.subtract(bg, list.get(i).getZd013Quantity());
				}
			}
		}
		if(bg.compareTo(new BigDecimal(0))==1){
			return false;
		}
		return true;
	}
	
	private List<LogicProductionPlanItemDO> findByIdItem(LogicProductionPlanDO curAP,boolean bl){
		List<LogicProductionPlanItemDO> list = new ArrayList<LogicProductionPlanItemDO>();
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty("removed");
		if(bl){
			scs.addCondition("zd001FormCode", curAP.getZd001FormCode(), SearchCondition.OP_NOTEQUAL);
		}
		scs.addCondition("zd002OriCode", curAP.getZd002OriCode(), SearchCondition.OP_EQUAL);
		scs.addCondition("zd008Billstatus", BillStatusUtil.PROPLAN_BILL_STATUS_ONEW, SearchCondition.OP_NOTEQUAL);
		List<LogicProductionPlanDO> result = this.findListByExample(scs).getResults();
		if(result!=null&&!result.isEmpty()&&result.size()>0){
			for(int i=0;i<result.size();i++){
				List<LogicProductionPlanItemDO> dispatItem = this.findPlanItemList(result.get(i).getId());
				list.addAll(dispatItem);
			}
		}
		return list;
	}
	
	@Override
	public void deleteBizRemovedBySaleId(String backSaleId)throws SyBaseException{
		SearchConditions planScs = new SearchConditions();
		planScs.addCondition("zd002OriId", backSaleId, SearchCondition.OP_EQUAL);
		List<LogicProductionPlanDO> planList = logicProductionPlanDAO.find(planScs);
		if(planList==null||planList.isEmpty()||planList.size()==0){
			return;
		}else{
			for(LogicProductionPlanDO plan : planList){
				if(plan==null||StringUtils.isBlank(plan.getId())){
					continue;
				}
				logicProductionPlanDAO.deleteBizRemoved(plan.getId());
			}
		}
	}
}
